/**
 * Created by yuris on 10.02.15.
 */
package view {
import InterfaceObjects.BottomPanel.BottomPanel;
import InterfaceObjects.BottomPanel.PaintItem;
import InterfaceObjects.BottomPanel.ShelfItem;
import InterfaceObjects.BottomPanel.WarehouseItem;

import com.greensock.TweenMax;
import com.greensock.easing.Bounce;
import com.greensock.easing.Quad;

import flash.geom.Point;

import flash.geom.Point;

import messages.ModelToViewMessage;
import messages.ViewToControllerMessage;

import model.Constants;

import model.Constants;

import model.objects.ProductWarehouseData;
import model.WarehouseDataProxy;
import model.prototypes.ShelfProto;
import model.prototypes.ShopDesignItemProto;

import mvcexpress.mvc.Mediator;

import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.TouchEvent;
import starling.events.TouchEvent;
import starling.events.TouchPhase;

public class BottomPanelMediator extends Mediator {
    [Inject]
    public var bottomPanel:BottomPanel
    private var _currentTime:int = 0;
    private var _bottomPanelY:Number = 0;

    //private var _warehouseData:WarehouseData = null;
    override protected function onRegister():void {
        bottomPanel.scrollContainer.addEventListener(TouchEvent.TOUCH, HANDLER_scrollContainerTriggered);
        bottomPanel.addEventListener(BottomPanel.EVENT_BUTTON_TRIGGERED, HANDLER_topButtonTriggered)

        addHandler(WarehouseDataProxy.MESSAGE_UPDATE_WAREHOUSE, HANDLER_warehouseDataUpdate);
        addHandler(ModelToViewMessage.TIME_UPDATE, HANDLER_timeUpdate);

        addHandler(ModelToViewMessage.LOCK_BOTTOM_PANEL, HANDLER_toggleLock);
        addHandler(ModelToViewMessage.MODE_CHANGED, HANDLER_modeChanged);

        addHandler(ModelToViewMessage.NEW_FLOORS_AVAILABLE, HANDLER_newFloorsAvailable)
        addHandler(ModelToViewMessage.NEW_WALLS_AVAILABLE, HANDLER_newWallsAvailable)
        addHandler(ModelToViewMessage.NEW_SHELFS_AVAILABLE, HANDLER_newShelfsAvailable)


        bottomPanel.setTopButtonsVisibility(false,BottomPanel.TOP_BUTTONS_GROUP_INTERIOR,false);
        bottomPanel.setTopButtonsVisibility(true,BottomPanel.TOP_BUTTONS_GROUP_SIMULATION,false);
        bottomPanel.setCloseButtonVisibility(false);

    }


    private function HANDLER_modeChanged(params:Object):void {
        switch (params.mode){
            case Constants.MODE_SIMULATION:
                bottomPanel.setNavButtonsParam("visible", true);
                bottomPanel.touchable = bottomPanel.visible = true;
                bottomPanel.scrollContainer.touchable = true;
                bottomPanel.setTopButtonsVisibility(false,BottomPanel.TOP_BUTTONS_GROUP_INTERIOR);
                bottomPanel.setTopButtonsVisibility(true,BottomPanel.TOP_BUTTONS_GROUP_SIMULATION);
                bottomPanel.setCloseButtonVisibility(false);
                if(String(params.mode_old).indexOf(Constants.MODE_INTERIOR) >= 0){
                    bottomPanel.showSocialItems();
                }
                break;
            case Constants.MODE_INTERIOR:
                bottomPanel.setNavButtonsParam("visible", true);
                bottomPanel.touchable = bottomPanel.visible = true;
                bottomPanel.scrollContainer.touchable = true;
                bottomPanel.setTopButtonsVisibility(true,BottomPanel.TOP_BUTTONS_GROUP_INTERIOR);
                bottomPanel.setTopButtonsVisibility(false,BottomPanel.TOP_BUTTONS_GROUP_SIMULATION);
                bottomPanel.setCloseButtonVisibility(false);
                if(String(params.mode_old).indexOf(Constants.MODE_SIMULATION) >= 0){
                    bottomPanel.showShelfItems();
                }
                if(String(params.mode_old).indexOf(Constants.MODE_INTERIOR_MOVE_SHELF) >= 0){
                    TweenMax.to(bottomPanel, 0.5, {y:_bottomPanelY})
                }
                if(String(params.mode_old).indexOf(Constants.MODE_INTERIOR_MOVE_WALL_COVER) >= 0){
                    TweenMax.to(bottomPanel, 0.5, {y:_bottomPanelY})
                }
                if(String(params.mode_old).indexOf(Constants.MODE_INTERIOR_MOVE_DOOR) >= 0){
                    TweenMax.to(bottomPanel, 0.5, {y:_bottomPanelY})
                }
                break;
            case Constants.MODE_SIMULATION_PLACE_PRODUCT:
                bottomPanel.setNavButtonsParam("visible", false);
                bottomPanel.scrollContainer.touchable = false;
                bottomPanel.setTopButtonsVisibility(false,BottomPanel.TOP_BUTTONS_GROUP_SIMULATION);
                bottomPanel.setCloseButtonVisibility(true);
                break;
            case Constants.MODE_INTERIOR_PLACE_SHELF:
            case Constants.MODE_INTERIOR_PLACE_FLOOR:
            case Constants.MODE_INTERIOR_PLACE_WALL:
                if(params.mode_old != params.mode){
                    bottomPanel.setTopButtonsVisibility(false,BottomPanel.TOP_BUTTONS_GROUP_INTERIOR);
                    bottomPanel.setCloseButtonVisibility(true);
                }
                break;
            case Constants.MODE_INTERIOR_MOVE_SHELF:
            case Constants.MODE_INTERIOR_MOVE_WALL_COVER:
            case Constants.MODE_INTERIOR_MOVE_DOOR:
                if(params.mode_old != params.mode){
                    //bottomPanel.setTopButtonsVisibility(false,BottomPanel.TOP_BUTTONS_GROUP_INTERIOR);
                    bottomPanel.touchable = false;
                    this._bottomPanelY = bottomPanel.y
                    TweenMax.to(bottomPanel, 0.5, {delay: 0.0, y:"250",visible:false})
                }
                break;
        }
    }


    private function HANDLER_topButtonTriggered(event:Event):void {
        switch (event.data.buttonName){
            case BottomPanel.BUTTON_INTERIOR:
                sendMessage(ViewToControllerMessage.INTERFACE_LAYER_TOUCH, {type:Constants.TOUCH_BOTTOM_PANEL_INTERIOR_MODE_BUTTON});
                break;
            case BottomPanel.BUTTON_SIMULATION:
                sendMessage(ViewToControllerMessage.INTERFACE_LAYER_TOUCH, {type:Constants.TOUCH_BOTTOM_PANEL_SIMULATION_MODE_BUTTON});
                break;
            case BottomPanel.BUTTON_SHOP:
                this.bottomPanel.showSocialItems();
                break;
            case BottomPanel.BUTTON_WAREHOUSE:
                this.bottomPanel.showWarehouse();
                break;
            case BottomPanel.BUTTON_BUILD_OBJECT:
                this.bottomPanel.showShelfItems();
                break;
            case BottomPanel.BUTTON_PAINT_FLOOR:
                this.bottomPanel.showFloorPaintItems();
                break;
            case BottomPanel.BUTTON_PAINT_WALL:
                this.bottomPanel.showWallPaintItems();
                break;

            case BottomPanel.BUTTON_CLOSE:
                sendMessage(ViewToControllerMessage.INTERFACE_LAYER_TOUCH, {type:Constants.TOUCH_BOTTOM_PANEL_CLOSE_BUTTON});
                break;
        }
    }

    private var _bufShopDesignProtos:Vector.<ShopDesignItemProto>;
    private var _bufShopDesignItemProto:ShopDesignItemProto;
    private function HANDLER_newFloorsAvailable(params:Object):void {
        this._bufShopDesignProtos = params.floors as Vector.<ShopDesignItemProto>;
        for (var i:int = 0; i < this._bufShopDesignProtos.length; i++) {
            this._bufShopDesignItemProto = this._bufShopDesignProtos[i];
            bottomPanel.floorPaintItems.push(new PaintItem(this._bufShopDesignItemProto.id,Constants.PATH_FLOOR_SPRITES+"/"+this._bufShopDesignItemProto.spriteId, PaintItem.TYPE_FLOOR))
        }
    }
    private function HANDLER_newWallsAvailable(params:Object):void {
        this._bufShopDesignProtos = params.walls as Vector.<ShopDesignItemProto>;
        for (var i:int = 0; i < this._bufShopDesignProtos.length; i++) {
            this._bufShopDesignItemProto = this._bufShopDesignProtos[i];
            bottomPanel.wallPaintItems.push(new PaintItem(this._bufShopDesignItemProto.id,Constants.PATH_WALL_SPRITES+"/"+this._bufShopDesignItemProto.spriteId, PaintItem.TYPE_WALL))
        }
    }

    private var _bufShelfProtos:Vector.<ShelfProto>;
    private var _bufShelfProto:ShelfProto;
    private function HANDLER_newShelfsAvailable(params:Object):void {
        this._bufShelfProtos = params.shelfs as Vector.<ShelfProto>;
        for (var i:int = 0; i < this._bufShelfProtos.length; i++) {
            this._bufShelfProto = this._bufShelfProtos[i];
            bottomPanel.shelfItems.push(new ShelfItem(this._bufShelfProto.typemodel,Constants.PATH_SHELF_ICONS_SPRITES+"/icon_"+this._bufShelfProto.spriteId))
        }
    }


    private function HANDLER_toggleLock(params:Object):void {
        if(bottomPanel){
            bottomPanel.touchable = !Boolean(params.value);
        }
    }

    private function HANDLER_timeUpdate(param:Object):void {
        this._currentTime = param.time;
        this._updateWarehouseProductsDeliverTime(this._currentTime);
    }

    private var _bufWarehouseItem:WarehouseItem;
    private var _bufInt:int = 0;
    private function HANDLER_warehouseDataUpdate(parameters:Object):void {
        this._processWarehouseDataUpdate(parameters.command,parameters.param);
    }
    private var _oldProductBuf:ProductWarehouseData;
    private function _processWarehouseDataUpdate(commandName:String, param:Object):void {
        switch(commandName){
            case WarehouseDataProxy.COMMAND_UPDATE_PRODUCT:
                this._oldProductBuf = param.product_old;
                this._bufWarehouseItem = bottomPanel.warehouseItems[param.cellNum];
                if(param.product == null){//make the slot empty
                    this._updateWarehouseItem( this._bufWarehouseItem,param.product);

                    //if(this._oldProductBuf!= null && this._oldProductBuf.count > 0){//delete product
                        if(this._bufWarehouseItem.parent){
                            this._bufWarehouseItem.parent.addChild(this._bufWarehouseItem)
                            TweenMax.to(this._bufWarehouseItem,0.45,{ y:"-20", ease:Quad.easeOut});
                            TweenMax.to(this._bufWarehouseItem,0.8,{delay:0.45, y:"20", ease:Bounce.easeOut});
                        }
                    //}
                } else if((this._oldProductBuf == null || this._oldProductBuf.count == 0) && bottomPanel.currentTab == BottomPanel.TAB_WAREHOUSE){
                    TweenMax.delayedCall(0.8,this._animateAddProduct, [this._bufWarehouseItem,param.product]);
                } else {
                    this._updateWarehouseItem( this._bufWarehouseItem,param.product);
                }

                break;
            case WarehouseDataProxy.COMMAND_ADD_CELL:
                this._bufWarehouseItem = new WarehouseItem();
                bottomPanel.warehouseItems.push(this._bufWarehouseItem);
                if(bottomPanel.currentTab == BottomPanel.TAB_WAREHOUSE){
                    bottomPanel.showWarehouse();
                }
                break;
        }
    }

    private function _animateAddProduct(warehouseItem:WarehouseItem, product:ProductWarehouseData):void {
        warehouseItem.productIconTexture = Constants.PATH_PRODUCT_ICONS_SPRITES+"/icon_"+product.proto.spriteId;

        if(warehouseItem.parent){
            warehouseItem.parent.addChild(warehouseItem)
            warehouseItem.touchable = false;
            TweenMax.to(warehouseItem,0.45,{scaleX:1.3, scaleY:1.3, y:"-8",ease:Quad.easeOut});
            TweenMax.to(warehouseItem,0.4,{delay:0.45, scaleX:1, scaleY:1, y:"8", ease:Bounce.easeOut, onComplete:this._updateWarehouseItem, onCompleteParams:[warehouseItem,product]});
        } else {
            this._updateWarehouseItem(warehouseItem, product);
        }
    }

    private function _updateWarehouseItem(warehouseItem:WarehouseItem, product:ProductWarehouseData):void {
        if(product == null){
            warehouseItem.amount = "empty";
            warehouseItem.deliverSecondsRest = -1;
            warehouseItem.productIconTexture = null;
        } else {
            warehouseItem.amount = product.count + "kg";
            warehouseItem.deliverTime = product.deliverTime;
            warehouseItem.deliverSecondsRest = warehouseItem.deliverTime - this._currentTime;
            warehouseItem.productIconTexture = Constants.PATH_PRODUCT_ICONS_SPRITES+"/icon_"+product.proto.spriteId;
            warehouseItem.touchable = true;
        }
    }
    private var _i:int = 0;
    private function _updateWarehouseProductsDeliverTime(_currentTime:int):void {
        this._bufWarehouseItems = bottomPanel.warehouseItems;
        for (_i = 0; _i < _bufWarehouseItems.length; _i++) {
            this._bufWarehouseItem = _bufWarehouseItems[_i];
            if(this._bufWarehouseItem.deliverTime >= this._currentTime){
                this._bufWarehouseItem.deliverSecondsRest = this._bufWarehouseItem.deliverTime - this._currentTime;
            }
        }
    }


    //----------
    //Touch process
    //------------------
    private var _bufTouchPoint:Point = new Point();
    private var _bufTouchTarget:DisplayObject;
    private var _bufPoint:Point;
    private function HANDLER_scrollContainerTriggered(event:TouchEvent):void {
        if(event.touches[0]){
            if(event.touches[0].phase == TouchPhase.BEGAN){
                 event.touches[0].getLocation(bottomPanel,this._bufTouchPoint);
            } else if(event.touches[0].phase == TouchPhase.ENDED){
                if(Point.distance(this._bufTouchPoint,event.touches[0].getLocation(bottomPanel)) < 5)
                {
                    switch (bottomPanel.currentTab){
                        case BottomPanel.TAB_WAREHOUSE:
                            this._checkWarehouseTouch(event);
                            break;
                        case BottomPanel.TAB_PAINT_FLOOR:
                            //this._checkFloorPaintTouch(event);
                            this._checkItemTouch(event,bottomPanel.floorPaintItems,Constants.TOUCH_BOTTOM_PANEL_FLOORPAINT);
                            break;
                        case BottomPanel.TAB_PAINT_WALL:
                            this._checkItemTouch(event,bottomPanel.wallPaintItems,Constants.TOUCH_BOTTOM_PANEL_WALLPAINT);
                            //this._checkWallPaintTouch(event);
                            break;
                        case BottomPanel.TAB_SHELFS:
                                //TODO:check shelfs touch
                            this._checkItemTouch(event,bottomPanel.shelfItems,Constants.TOUCH_BOTTOM_PANEL_SHELFS);
                            break;
                    }

                }
            }
        }
    }

    private var _bufItem:DisplayObject;
    private function _checkItemTouch(event:TouchEvent,itemsArray:Object, touchMessageType:String):void {
        for (_bufInt = 0; _bufInt < itemsArray.length; _bufInt++) {
            this._bufItem = itemsArray[_bufInt];
            if(event.getTouch(this._bufItem, TouchPhase.ENDED)){
                this._bufPoint = bottomPanel.scrollContainer.localToGlobal(new Point(this._bufItem.x,this._bufItem.y));
                this._bufPoint.x -= bottomPanel.scrollContainer.horizontalScrollPosition;
                sendMessage(ViewToControllerMessage.INTERFACE_LAYER_TOUCH, {type:touchMessageType, cell_num:_bufInt,item_id:(this._bufItem as Object).id, item_pos:this._bufPoint})
            }
        }
    }


    private function _checkWarehouseTouch(event:TouchEvent):void {
        this._bufWarehouseItems = this.bottomPanel.warehouseItems;
        for (_bufInt = 0; _bufInt < _bufWarehouseItems.length; _bufInt++) {
            this._bufWarehouseItem = this._bufWarehouseItems[_bufInt];
            if(this._bufWarehouseItem.deliverNowButton.visible){
                if(event.getTouch(this._bufWarehouseItem.deliverNowButton, TouchPhase.ENDED)){
                    trace("Touch: Button in "+this._bufWarehouseItem);
                    //TODO: deliverNow process
                }
            } else
            if(event.getTouch(this._bufWarehouseItem, TouchPhase.ENDED)){
                this._bufPoint = bottomPanel.scrollContainer.localToGlobal(new Point(this._bufWarehouseItem.x,this._bufWarehouseItem.y));
                this._bufPoint.x -= bottomPanel.scrollContainer.horizontalScrollPosition;
                sendMessage(ViewToControllerMessage.INTERFACE_LAYER_TOUCH, {type:Constants.TOUCH_BOTTOM_PANEL_WAREHOUSE_ITEM, cell_num:_bufInt, item_pos:this._bufPoint})
                break;
            }
        }
    }


    private var _bufWarehouseItems:Vector.<WarehouseItem>;




    override protected function onRemove():void {

    }


}
}
